package com.thinklib.controller;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;

@Controller
@RequestMapping("/api/v1/book/")
public class PreviewBookController {

    @Value("${file.upload.url}")
    private String url;
    /**
     * @mdesc  预览PDF
     * @param filename
     * @Test_URL http://localhost:8080/api/v1/book/preview?filename=JMeter%E6%8E%A5%E5%8F%A3%E5%92%8C%E6%80%A7%E8%83%BD%E6%B5%8B%E8%AF%95.pdf
     */
    @RequestMapping("/preview")
    public void pdfStreamHandler(@RequestParam("filename")String filename, HttpServletResponse response) {

        File file = new File(url + filename);
        if (file.exists()){
            try {
                BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
                byte[] data = new byte[bis.available()];
                bis.read(data);
                response.getOutputStream().write(data);
                bis.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }else{
            return;
        }
    }
}
